package com.yitao.cms.service.operatorLog;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.service.GenericEntityService;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.dto.operatorLog.OperatorLogDto;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.model.operatorLog.OperatorLogModel;
import com.yitao.cms.model.operatorLog.QOperatorLogModel;
import com.yitao.cms.service.user.cmsUser.OperationUserService;
import com.yitao.cms.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: wuwenlong
 * @Date: 2018/8/6 0006 15:36
 * @Description:
 */
@Service
public class OperatorLogService extends GenericEntityService<OperatorLogModel, OperatorLogDto, QOperatorLogModel> {
    public OperatorLogService(EntityManager entityManager) {
        super(entityManager);
    }
    @Autowired
    private OperationUserService userService;
    /**
     * 添加日志记录
     */
    @Transactional
    public DataOutput operatorLogAdd(OperatorLogDto operatorLogDto, HttpServletRequest request) {
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession!=null && userSession.getId()!=null){
            String nowDate = DateUtils.nowDate("yyyy-MM-dd HH:mm:ss");
            OperatorLogModel operatorLogModel = new OperatorLogModel();
            BeanUtils.copyProperties(operatorLogDto, operatorLogModel);
            operatorLogModel.setCreateBy(String.valueOf(userSession.getId()));
            operatorLogModel.setOperatorName(userSession.getUserName());
            operatorLogModel.setCreateTime(nowDate);
            repository.save(operatorLogModel);
        }
        return new DataOutput(CommonStatus.SUCCESS);
    }

    /**
     * 日志记录查询
     * @param targetType
     * @param IP
     * @param staDate
     * @param endDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PagedOutput findSystermLog(String targetType,String operatorURL,String operatorName,String IP,String staDate, String endDate,int pageNo,int pageSize){
        PagedInput pagedInput = new PagedInput();
        pagedInput.setPage(pageNo);
        pagedInput.setSize(pageSize);
        PagedOutput<OperatorLogModel> pagedOutput = null;
        List<OperatorLogDto> operatorLogDtoList = null;
        //判断时间不传的情况
        String nowDate = DateUtils.nowDate("yyyy-MM-dd");
        final String staDate1;
        final String endDate1;
        if(StringUtils.isEmpty(staDate)){
            staDate1="1970-01-01 00:00:00.0";
        }else {
            staDate1=staDate+" 00:00:00.0";
        }
        if (StringUtils.isEmpty(endDate)){
            endDate1=nowDate+" 23:59:59.0";
        }else{
            endDate1=endDate+" 23:59:59.0";
        }
        try {
            pagedOutput = repository.pagingList(PredicateBuilder.conjunction()
                    .ifHasTextThenAnd(targetType,() -> Q.targetType.eq(targetType))
                    .ifHasTextThenAnd(operatorURL,() -> Q.operatorUrl.eq(operatorURL))
                    .ifHasTextThenAnd(operatorName,() -> Q.operatorName.like("%"+operatorName+"%"))
                    .ifHasTextThenAnd(IP,() ->Q.remoteAddr.eq(IP))
                    .ifTrueThenAnd(staDate != null && !"".equals(staDate) && endDate != null && !"".equals(endDate), ()
                                    -> Q.createTime.between(staDate1, endDate1))
                    .get(), pagedInput, new OrderSpecifier<>(Order.DESC,Q.createTime)
                    );


            if(pagedOutput!=null && pagedOutput.getData()!=null){
                operatorLogDtoList = pagedOutput.getData().stream().map(it->
                {
                OperatorLogDto operatorLogDto = new OperatorLogDto();
                    BeanUtils.copyProperties(it, operatorLogDto);
                    //补充数据
                    if(!StringUtils.isEmpty(operatorLogDto.getCreateBy())){
                    OperationUserCmsModel UserInfoModel=userService.findUserInfoById(Long.valueOf(operatorLogDto.getCreateBy()));
                    if(UserInfoModel!=null){//拼接操作人姓名
                        operatorLogDto.setCreateBy(UserInfoModel.getUserName());
                    }
                     }
                    return operatorLogDto;
                }).collect(Collectors.toList());

            }
            return new PagedOutput(pagedInput,pagedOutput.getTotalElements(),operatorLogDtoList);

        } catch (Exception e) {
            logger.error("查询日志记录失败{}",e.getMessage());
            return new PagedOutput(pagedInput,0,null);
        }
    }

}
